package com.liurong.netty.v2.client;

import java.util.concurrent.TimeUnit;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;

public class ChatClientInitializer extends ChannelInitializer<SocketChannel> {
	private ChatClient chatClient;

	public ChatClientInitializer() {
		super();
	}

	public ChatClientInitializer(ChatClient chatClient) {
		this.chatClient = chatClient;
	}

	@Override
	protected void initChannel(SocketChannel ch) throws Exception {
		// 信道管道
		ChannelPipeline pipeline = ch.pipeline();

		// 心跳
		pipeline.addLast("heartbeat", new IdleStateHandler(0, 0, 4, TimeUnit.SECONDS));

		pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
		// 编码
		pipeline.addLast("decoder", new StringDecoder());
		// 解码
		pipeline.addLast("encoder", new StringEncoder());

		// 消息处理器
		pipeline.addLast("handler", new ChatClientHandler(chatClient));
	}

}
